package controllers

import (
	"blog/models"
	"blog/syserror"
	"errors"
	"strings"
)

type UserController struct {
	BaseController
}

//@router /login [post]
func (this *UserController) Login() {

	//页面传过来的username
	phone := this.GetMustString("username", "用户名不能为空！")

	//页面传过来的passord
	pwd := this.GetMustString("password", "密码不能为空！")

	user, err := models.QueryUserByUnameAndPwd(phone, pwd)

	if err != nil {
		this.Abort500(syserror.New(301, "登录失败！", err))
	}

	this.SetSession(SessionUserKey, user)

	this.JsonReturn(0, "登录成功!", "/")

}

//@router /logout [get]
func (this *UserController) Logout() {
	this.MustLogin()
	this.DelSession(SessionUserKey)
	this.Redirect("/", 302)
}

//@router /register [post]
func (this *UserController) Register() {
	//账号，昵称，密码，验证码

	phone := this.GetMustString("username", "手机号不能为空！")

	//页面传过来的passord
	pwd := this.GetMustString("password", "密码不能为空！")

	//页面传过来的确认密码
	repwd := this.GetMustString("repassword", "确认密码不能为空！")

	//页面传过来的验证码
	//code := this.GetMustString("code", "验证码不能为空！")

	if strings.Compare(pwd, repwd) != 0 {
		this.Abort500(errors.New("两次输入的密码不一致！"))
	}

	if u, err := models.QueryUserByPhone(phone); err == nil && u.ID > 0 {
		this.Abort500(errors.New("手机号已存在！"))
	}

	if err := models.SaveUser(&models.User{
		Name:   "YK" + phone,
		Phone:  phone,
		Pwd:    pwd,
		Avatar: "/static/img/avatar.png",
		Role:   1,
	}); err != nil {
		this.Abort500(syserror.New(301, "用户注册失败！", err))
	}

	this.JsonReturn(0, "注册成功！", "/user")
}
